package com.example.pdftoofd.service;

import com.example.pdftoofd.entity.HistoryEntity;
import com.example.pdftoofd.utils.MyFileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class HistoryService {
    @Value("${filePath.root:./file}" + "${filePath.history:/history/}")
    private String logPath;

    @PostConstruct
    public void init() {
        MyFileUtil.ifNotExistsAndMkdir(logPath);
    }

    public void writeHistory(String history) {
        cleanHistory();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String historyPath = logPath + simpleDateFormat.format(new Date()) + ".log";
        MyFileUtil.writeLineFile(historyPath, history);
    }

    public List<HistoryEntity> readHistory() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String historyPath = logPath + simpleDateFormat.format(new Date()) + ".log";
        return MyFileUtil.readLineFile(historyPath);
    }

    public List<HistoryEntity> readHistory(String date) {
        File file = new File(logPath);
        String[] historyList = file.list();
        for (String history : historyList) {
            if (history.contains(date)) {
                String historyPath = logPath + history;
                return MyFileUtil.readLineFile(historyPath);
            }
        }
        return null;
    }

    public void cleanHistory() {
        File file = new File(logPath);
        String[] list = file.list();
        Arrays.sort(list);
        int index = list.length - 7;
        for (int i = 0; i < list.length; i++) {
            if (index > 0) {
                if (i < index) {
                    new File(logPath + list[i]).delete();
                }
            }
        }
    }
}
